<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\RedisEnum;
use app\model\ClientAccountModel;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

class RefreshYesterdayPicReportListWork extends BaseWork implements ListWorkInterface
{
    public function getListKey(int $mediaId = 0, $date = 0): string
    {
        $key = '';
        $date = $date ?: date('Ymd');
        switch ($mediaId) {
            case CommonEnum::OE_MEDIA:
                $key = 'task:material:oe:yesterday_pic_daily:' . $date . ':' . RedisEnum::REDIS_LIST;
                break;
            case CommonEnum::KS_MEDIA:
                $key = 'task:material:ks:yesterday_pic_daily:' . $date . ':' . RedisEnum::REDIS_LIST;
                break;
            case CommonEnum::QQ_MEDIA:
                $key = 'task:material:qq:yesterday_pic_daily:' . $date . ':' . RedisEnum::REDIS_LIST;
                break;
        }
        return $key;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('refresh_yesterday_pic_report_work');
        $this->setDescription('刷新拉取昨日图片报表队列');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体id')
            ->addArgument('date', null, 'date');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $mediaId = intval($input->getArgument('media_id'));
        $date = intval($input->getArgument('date'));
        $output->writeln('=======刷新拉取昨日图片报表开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            $redis = Cache::store('redis')->handler();
            $key = $this->getListKey($mediaId, $date);
            $accounts = $this->_getMediaAccount($mediaId);
            if ($accounts) {
                foreach ($accounts as $v) {
                    // 过滤已删除账户
                    if (! self::filterAccount($v)) {
                        continue;
                    }
                    $value = $v . '_' . 0 . '_' . time();
                    $redis->rPush($key, $value);
                }
            }
        } catch (\Exception $e) {
            $output->writeln('=======刷新拉取昨日图片报表有误：' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
        }
        $output->writeln('=======刷新拉取昨日图片报表结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取媒体app-token分页.
     */
    private function _getMediaAccount(int $mediaId): array
    {
        return ClientAccountModel::where('media_id', $mediaId)
            ->where('auth_valid', 1)
            ->order('cost_sort desc,id desc')
            ->column('advertiser_id');
    }
}
